import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 定义公共API列表（不需要验证token的API）
const PUBLIC_APIS = [
  '/auth/login',
  '/auth/register',
  '/auth/tenants',
  '/auth/forgot-password'
];

// 检查URL是否为公共API
const isPublicApi = (url) => {
  return PUBLIC_APIS.some(publicUrl => url.includes(publicUrl));
};

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.log('API请求配置:', {
      method: config.method,
      url: config.url,
      baseURL: config.baseURL,
      headers: config.headers,
      data: config.data
    });
    
    // 如果是公共API，不需要添加token
    if (isPublicApi(config.url)) {
      console.log('访问公共API，无需token验证');
      return config;
    }
    
    // 从localStorage获取token并确保它是有效的
    const token = localStorage.getItem('token');
    
    // 检查token是否存在且非undefined
    if (token && token !== 'undefined' && token.length > 10) {
      console.log('已找到有效token:', token.substring(0, 10) + '...');
      config.headers.Authorization = `Bearer ${token}`;
      console.log('已添加Authorization头:', config.headers.Authorization);
    } else {
      console.warn('未找到有效token，请求可能需要认证:', config.url);
      // 如果token无效，从localStorage中移除它
      if (token === 'undefined' || (token && token.length < 10)) {
        console.error('检测到无效token，正在清除...');
        localStorage.removeItem('token');
      }
    }
    
    return config;
  },
  error => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('API响应成功:', response.config.url);
    return response;
  },
  error => {
    console.error('API响应错误:', error.config?.url, error.message);
    
    // 检查是否有响应
    if (error.response) {
      console.error('错误状态码:', error.response.status);
      console.error('错误数据:', error.response.data);
      
      // 处理401未授权错误
      if (error.response.status === 401) {
        console.error('授权失败: 令牌无效或已过期');
        
        // 清除本地存储的token
        localStorage.removeItem('token');
        
        // 获取当前路径，以便登录后重定向回来
        const currentPath = window.location.pathname;
        
        // 如果不是在登录页，则跳转到登录页
        if (!currentPath.includes('/login')) {
          alert('您的登录已过期或无效，需要重新登录');
          // 跳转到登录页，并记录原始URL用于登录后重定向
          window.location.href = `/login?redirect=${encodeURIComponent(currentPath)}`;
        }
      }
    } else {
      console.error('网络错误或请求被取消');
    }
    
    return Promise.reject(error);
  }
);

export default api;

export const getProjects = () => api.get('/projects');
export const getProjectDetail = (id) => api.get(`/projects/${id}`);
export const createProject = (data) => api.post('/projects', data);
export const updateProject = (id, data) => api.put(`/projects/${id}`, data);
export const getProjectTasks = (id) => api.get(`/projects/${id}/tasks`);
export const createProjectTask = (projectId, data) => api.post(`/projects/${projectId}/tasks`, data);

export const getTaskDetail = (taskId) => {
  return api.get(`/tasks/${taskId}/detail`);
};
export const updateTask = (id, data) => api.put(`/tasks/${id}`, data);
export const manualBreakdownTask = (taskId, tasksData) => api.post(`/tasks/${taskId}/manual-breakdown`, tasksData);
export const getTaskBreakdownVersions = (taskId) => api.get(`/tasks/${taskId}/breakdown-versions`);
export const getBreakdownVersionDetail = (versionId) => api.get(`/breakdown-versions/${versionId}`);
export const updateBreakdownVersionStatus = (versionId, status) => api.put(`/breakdown-versions/${versionId}/status`, { status });
export const updateSubtask = (subtaskId, updateData) => api.put(`/subtasks/${subtaskId}`, updateData);

export const getSubTasks = (breakdownId) => api.get(`/tasks/breakdown/${breakdownId}/subtasks`);
export const getAtomicTasks = () => api.get('/tasks/atomic');
export const getBlockedTasks = () => api.get('/tasks/blocked');

export const executeTask = (subtaskId, executor = 'manual', result = '') => 
  api.post(`/subtasks/${subtaskId}/execute`, { executor, result });
export const submitExecutionResult = (executionId, result) => api.post(`/executions/${executionId}/result`, result);
export const reviewExecution = (executionId, reviewData) => api.post(`/executions/${executionId}/review`, reviewData);
export const rollbackExecution = (executionId, reason) => api.post(`/executions/${executionId}/rollback`, { reason });

export const getTaskDependencies = (taskId) => api.get(`/tasks/${taskId}/dependencies`);
export const addTaskDependency = (taskId, dependencyId) => api.post(`/tasks/${taskId}/dependencies`, { dependency_id: dependencyId });
export const removeTaskDependency = (taskId, dependencyId) => api.delete(`/tasks/${taskId}/dependencies/${dependencyId}`);

export const getTaskProgress = (taskId) => api.get(`/tasks/${taskId}/progress`);
export const updateTaskProgress = (taskId, progressData) => api.post(`/tasks/${taskId}/progress`, progressData);

export const getUserSettings = (username) => api.get(`/user/settings?username=${username}`);
export const updateUserSettings = (data) => api.post('/user/settings', data);

export const getSubtaskGitInfo = (subtaskId) => api.get(`/subtasks/${subtaskId}/git-info`);

// 添加删除版本的API函数
export const deleteBreakdownVersion = (versionId) => {
  console.log(`发送删除版本请求: /breakdown-versions/${versionId}，方法: DELETE`);
  return api.delete(`/breakdown-versions/${versionId}`);
}; 